package com.example.pm.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.pm.common.result.R;
import com.example.pm.common.utils.ExcelUtils;
import com.example.pm.common.utils.StringUtils;
import com.example.pm.domain.Car;
import com.example.pm.domain.Employee;
import com.example.pm.mapper.EmployeeMapper;
import com.example.pm.service.CarService;
import com.example.pm.service.ImportService;
import com.example.pm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ImportServiceImpl implements ImportService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private CarService carService;
    @Autowired
    private UserService userService;

    @Override
    public R<String> importEmployees(MultipartFile[] files) {
        List<String> list = ExcelUtils.uploadExcel(files);
        if (list.isEmpty())
            return R.warn("导入失败，文件数据格式错误");
        else {
            List<Employee> lists = new ArrayList<>();
            list.forEach(path -> {
                lists.addAll(ExcelUtils.parseFromExcel(path, Employee.class));
            });
            List<String> list1 = employeeMapper.selectList(new LambdaQueryWrapper<>()).stream().map(Employee::getSfz).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
            List<Employee> list2 = lists.stream().filter(o -> !list1.contains(o.getSfz()))
                    .peek(o -> {
                        o.setBmxy("未签");
                        o.setTxid(1);
                    }).collect(Collectors.toList());
            if (!list2.isEmpty()) {
                employeeMapper.insertList(list2);
                userService.createUserRedis();
                return R.ok("导入成功，共计" + list2.size() + "条数据");
            } else {
                return R.warn("导入失败，文件中无数据");
            }

        }
    }

    @Override
    public R<String> importCars(MultipartFile[] files) {
        List<String> list = ExcelUtils.uploadExcel(files);
        if (list.isEmpty())
            return R.warn("导入失败，文件数据格式错误");
        else {
            List<Car> lists = new ArrayList<>();
            list.forEach(path -> {
                lists.addAll(ExcelUtils.parseFromExcel(path, Car.class));
            });
            if (!lists.isEmpty()) {
                carService.insertList(lists);
                carService.createCarRedis();
                return R.ok("导入成功，共计" + lists.size() + "条数据");
            } else {
                return R.warn("导入失败，文件中无数据");
            }
        }
    }
}
